package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.MediaThreadLocalUtil;
import com.heima.media.dto.*;
import com.heima.media.entity.WmMaterial;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmNewsMaterial;
import com.heima.media.entity.WmUser;
import com.heima.media.feign.ApArticleClients;
import com.heima.media.mapper.WmNewsMapper;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsMaterialService;
import com.heima.media.service.IWmNewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.media.service.IWmUserService;
import com.heima.media.vo.WmNewsVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.json.Json;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-06-21
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements IWmNewsService {
    @Autowired
    @Lazy//解决循环依赖的问题
    IAuditService auditService;

    @Autowired
    private IWmUserService userService;

    @Autowired
    private IWmUserService iWmUserService;

    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Override
    public ResponseResult findPageByName(WmNewsDto wmNewsDto) {
        //构建分页
        Page<WmNews> page = new Page<>(wmNewsDto.getPage(), wmNewsDto.getSize());
        //构建查询条件
        LambdaQueryWrapper<WmNews> query = new LambdaQueryWrapper<>();
        //根据标题迷糊查询
        if (!StringUtils.isEmpty(query)) {
            query.like(WmNews::getTitle, wmNewsDto.getTitle());
        }
        if (wmNewsDto.getStatus()!=null){
            query.eq(WmNews::getStatus,wmNewsDto.getStatus());
        }
        query.orderByDesc(WmNews::getPublishTime);
        IPage<WmNews> page1 = this.page(page, query);
        long total = page1.getTotal();
        List<WmNews> records = page1.getRecords();

        ArrayList<WmNewsVo> vos = new ArrayList<>();
        for (WmNews wmNews : records) {
            WmNewsVo vo=new WmNewsVo();
            BeanUtils.copyProperties(wmNews,vo);
            WmUser byId = userService.getById(wmNews.getUserId());
            vo.setAuthorName(byId.getName());
            vos.add(vo);
        }

        PageResponseResult result = new PageResponseResult(wmNewsDto.getPage(), wmNewsDto.getSize(), total, vos);

        return result;

    }

    /**
     * 内容列表查询
     *
     * @param newsPageDto
     * @return
     */
    @Override
    public ResponseResult listPage(WmNewsPageDto newsPageDto) {
        Page<WmNews> page = new Page<>(newsPageDto.getPage(), newsPageDto.getSize());
        LambdaQueryWrapper<WmNews> query = new LambdaQueryWrapper<>();
        //根据文章状态查询
        if (newsPageDto.getStatus() != null) {
            query.eq(WmNews::getStatus, newsPageDto.getStatus());
        }
        //根据关键字模糊查询
        if (!StringUtils.isEmpty(newsPageDto.getKeyword())) {
            query.like(WmNews::getTitle, newsPageDto.getKeyword());
        }
        //根据频道列表查询
        if (newsPageDto.getChannelId() != null) {
            query.eq(WmNews::getChannelId, newsPageDto.getChannelId());
        }
        //发布日期  : 开始时间-->结束时间
        if (newsPageDto.getBeginPubDate() != null) {
            query.gt(WmNews::getPublishTime, newsPageDto.getBeginPubDate());
        }
        if (newsPageDto.getEndPubDate() != null) {
            query.le(WmNews::getPublishTime, newsPageDto.getEndPubDate());
        }
        //获取当前用户
        User user = MediaThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //当前用户查询
        query.eq(WmNews::getUserId, user.getUserId());
        //按照时间顺序查询
        query.orderByDesc(WmNews::getPublishTime);
        Page<WmNews> newsPage = this.page(page, query);

        PageResponseResult result = new PageResponseResult(newsPageDto.getPage(), newsPageDto.getSize(), newsPage.getTotal(), newsPage.getRecords());

        return result;
    }

    @Value("${topic.upDownTopic}")
    private String upDownTopic;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    @Override
    public ResponseResult xiajia(DownDto dto) {
        //根据id查询文章
        Integer id = dto.getId();
        WmNews byId = this.getById(id);
        //判断文章是否存在
        if (byId==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断文章是否已经发布
        if (byId.getStatus()!=9){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        byId.setEnable(dto.getEnable()==0 ?false:true);
        this.updateById(byId);

        //同步到article
        //发信息到kafka
        System.out.println("开始发送信息");
        String key=byId.getArticleId().toString();
        String value=dto.getEnable().toString();
        System.out.println("发送信息成功"+"key:"+key+"value:"+value);
        kafkaTemplate.send(upDownTopic,key,value);
        return ResponseResult.okResult();
    }



    /**
     * 发布文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submit(WmNewsDtoDto dto) {
        //判断用户是否登录
        User user = MediaThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //如果有id
        if (dto.getId() != null) {
            deleteRelation(dto.getId());
        }

        //没有id,新增文章
        WmNews wmNews = new WmNews();
        //属性拷贝
        BeanUtils.copyProperties(dto, wmNews);
        wmNews.setUserId(user.getUserId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setImages(JSON.toJSONString(dto.getImages()));
        //从前端传递的内容中提取图片
        List<ImageDto> content = getImagesFromContent(dto.getContent());
        if (dto.getType() == -1) {
            //判断内容图片的个数
            if (content.size() <= 0) {
                //无图
                wmNews.setType(0);
            } else if (content.size() < 3) {
                //单图
                wmNews.setType(1);
                List<ImageDto> imageDtos = content.subList(0, 1);
                wmNews.setImages(JSON.toJSONString(imageDtos));
            } else {
                //多图
                wmNews.setType(3);
                List<ImageDto> imageDtos = content.subList(0, 3);
                wmNews.setImages(JSON.toJSONString(imageDtos));
            }
        }
        //保存文章
        this.save(wmNews);


        //判断是否存为草稿
        if (dto.getStatus() ==1) {
            List<ImageDto> imageDtos = JSON.parseArray(wmNews.getImages(), ImageDto.class);
            saveRelation(wmNews, imageDtos, 1);
            saveRelation(wmNews, content, 0);


            //开启审核
            System.err.println("调用审核服务..........");
            auditService.audit(wmNews);

        }
        return ResponseResult.okResult();
    }

    /**
     * 媒体审核详情表
     * @param id
     * @return
     */
    @Override
    public ResponseResult<WmNewsVo> findNewsVoById(Integer id) {
        //查询文章
        WmNews byId = this.getById(id);
        //查询用户
        WmUser byId1 = userService.getById(byId.getUserId());

        WmNewsVo wmNewsVo=new WmNewsVo();
        //属性复制
        BeanUtils.copyProperties(byId,wmNewsVo);
        wmNewsVo.setAuthorName(byId1.getName());
        //返回前端
        return ResponseResult.okResult(wmNewsVo);
    }


    /**
     * 保存关联关系
     *
     * @param content
     * @param id
     * @param type
     */
    private void saveRelation(WmNews news, List<ImageDto> images, int type) {
        int ord = 0;
        // 构建图片对应关系
        // 遍历图片集合
        for (ImageDto image : images) {
            WmNewsMaterial newsMaterial = new WmNewsMaterial();
            newsMaterial.setMaterialId(image.getId());
            newsMaterial.setNewsId(news.getId());
            newsMaterial.setType(type);
            newsMaterial.setOrd(ord);
            // 保存
            newsMaterialService.save(newsMaterial);
            ord++;
        }
    }

    /**
     * 从前端传递的内容中提取图片
     *
     * @param content
     */
    private List<ImageDto> getImagesFromContent(String content) {
        ArrayList<ImageDto> contentImages = new ArrayList<>();
        List<ContentDto> dtos = JSON.parseArray(content, ContentDto.class);
        for (ContentDto dto : dtos) {
            if (dto.getType().equals("image")) {
                String value = dto.getValue();
                Integer id = dto.getId();
                ImageDto imageDto = new ImageDto(id, value);
                contentImages.add(imageDto);
            }
        }
        return contentImages;
    }

    @Autowired
    IWmNewsMaterialService newsMaterialService;

    /**
     * id不为空 删除素材-素材关联
     *
     * @param id
     */
    private void deleteRelation(Integer id) {
        LambdaQueryWrapper<WmNewsMaterial> query = new LambdaQueryWrapper<>();
        query.eq(WmNewsMaterial::getNewsId, id);
        newsMaterialService.remove(query);
    }


    @Override
    public List<WmNews> cha(WmNews wmNews) {
        LambdaQueryWrapper<WmNews> query = new LambdaQueryWrapper<>();
        System.err.println(wmNews.getTitle1());
        query.like(WmNews::getTitle,wmNews.getTitle1());
      return this.list(query);

    }

}
